package com.ruoyi.system.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.system.domain.WGood;
import com.ruoyi.system.domain.WGoodsRecords;
import com.ruoyi.system.domain.WOrder;
import com.ruoyi.system.domain.WOrderGood;
import com.ruoyi.system.domain.WOrderOpeara;
import com.ruoyi.system.domain.vo.WGoodExcel;
import com.ruoyi.system.domain.vo.WOrderGoodVO;
import com.ruoyi.system.domain.vo.WOrderVO;
import com.ruoyi.system.mapper.SysDeptMapper;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.mapper.WGoodMapper;
import com.ruoyi.system.mapper.WOrderGoodMapper;
import com.ruoyi.system.mapper.WOrderMapper;
import com.ruoyi.system.mapper.WOrderOpearaMapper;
import com.ruoyi.system.service.IWGoodService;
import com.ruoyi.system.service.IWOrderGoodService;
import com.ruoyi.system.service.IWOrderService;

/**
 * 物料订单Service业务层处理
 * 
 * @author ruoyi
 * @date 2021-12-05
 */
@Service
public class WOrderServiceImpl implements IWOrderService 
{
    @Autowired
    private WOrderMapper wOrderMapper;
    @Autowired
    private WGoodMapper wGoodMapper;
    @Autowired
    private SysUserMapper SysUserMapper;
    @Autowired
    private SysDeptMapper sysDeptMapper;
    @Autowired
    private WOrderGoodMapper wOrderGoodMapper;
    @Autowired
    private WOrderOpearaMapper wOrderOpearaMapper;
    @Autowired
    private IWGoodService iWGoodService;
    
    @Override
    public R complete(Long id) {
    	WOrder selectWOrderById = wOrderMapper.selectWOrderById(id);
    	Integer orderStatus = selectWOrderById.getOrderStatus();
    	if (orderStatus.intValue() == 4 ) return R.error("订单已经完成");
       	Long productNumber = selectWOrderById.getProductNumber();
       	Long goodNumber = selectWOrderById.getGoodNumber();
       	Long badNumber = selectWOrderById.getBadNumber();
       	Long cha = productNumber.longValue() - goodNumber.longValue() - badNumber.longValue();
       	if (cha.longValue() > 0l) {
       		WOrderGood wOrderGood = new WOrderGood();
        	wOrderGood.setOrderId(id);
    		List<WOrderGood> selectWOrderGoodList = wOrderGoodMapper.selectWOrderGoodList(wOrderGood );
    		
    		for (WOrderGood e : selectWOrderGoodList) {
    			WGoodsRecords wGoodsRecords = new WGoodsRecords();
    			wGoodsRecords.setChangeNumber(new Integer(cha.toString())  * e.getQuantity().intValue());
    			wGoodsRecords.setGoodsId(e.getGoodsId());
    			wGoodMapper.updateWGoodComplete(wGoodsRecords );;
    		}
       		
		}
       	WOrder wOrder = new WOrder();
       	wOrder.setId(id);
       	wOrder.setOrderStatus(4);
		wOrderMapper.updateWOrder(wOrder );
    	return R.success();
    }
    
    /**
     * 查询物料订单
     * 
     * @param id 物料订单主键
     * @return 物料订单
     */
    @Override
    public WOrderVO selectWOrderById(Long id)
    {
    	WOrderVO wOrderVO = new WOrderVO();
    	WOrder selectWOrderById = wOrderMapper.selectWOrderById(id);
    	BeanUtils.copyProperties(selectWOrderById, wOrderVO);
    	
    	WOrderGood wOrderGood = new WOrderGood();
    	wOrderGood.setOrderId(id);
		List<WOrderGoodVO> selectWOrderGoodVONewList = wOrderGoodMapper.selectWOrderGoodVONewList(wOrderGood );
		wOrderVO.setOrderGoodVOList(selectWOrderGoodVONewList);
        return wOrderVO;
    }
    
    @Override
    public WOrderVO hairOrderGood(Long orderId) {
    	WOrderVO wOrderVO = new WOrderVO();
    	WOrder selectWOrderById = wOrderMapper.selectWOrderById(orderId);
    	BeanUtils.copyProperties(selectWOrderById, wOrderVO);
    	
    	WOrderGood wOrderGood = new WOrderGood();
    	wOrderGood.setOrderId(orderId);
		List<WOrderGoodVO> selectWOrderGoodList = wOrderGoodMapper.selectWOrderGoodVOList(wOrderGood );
		
		for (WOrderGoodVO e : selectWOrderGoodList) {
			
			WGood selectWGoodById = wGoodMapper.selectWGoodById(e.getGoodsId());
			
			WOrderGood selectWOrderGoodNum = wOrderGoodMapper.selectWOrderGoodNumNotOrderId(e.getGoodsId(),orderId);
			long  a  = selectWGoodById.getNumber()-selectWOrderGoodNum.getNumber() ;
			e.setNumber( a < 0 ? 0 : a  );
		}
		wOrderVO.setOrderGoodVOList(selectWOrderGoodList);
        return wOrderVO;
    }
    /**
     * 查询物料订单列表
     * 
     * @param wOrder 物料订单
     * @return 物料订单
     */
    @Override
    public List<WOrderVO> selectWOrderList(WOrderVO wOrder)
    {
        return wOrderMapper.selectWOrderListNew(wOrder);
    }
    
    @Override
    public List<WGoodExcel> importDataGood(List<WGoodExcel> wGoodExcelList, Long customerId,   Long deptId) {
        List<WGood> selectWGoodListByPnList = wGoodMapper.selectWGoodListByPnList(wGoodExcelList, customerId, deptId);
        if (StringUtils.isEmpty(selectWGoodListByPnList)) {
        	  return wGoodExcelList;
		}else {
			for (WGoodExcel e : wGoodExcelList) {
				for (WGood wGood : selectWGoodListByPnList) {
					if (GoodUtil.checkEqu(wGood, e) ) {
						WOrderGood selectWOrderGoodNum = wOrderGoodMapper.selectWOrderGoodNum(wGood.getId());
						e.setNumber(wGood.getNumber()-selectWOrderGoodNum.getNumber());
					}
				}
			}
		}
        return wGoodExcelList;
    }
    
    
    @Transactional
    @Override
    public R addOrderPlan(WOrderVO wOrderVO) {
    	Long id = wOrderVO.getId();
    	if(id == null ) return R.error("没传id");
    	WOrder selectWOrderById = wOrderMapper.selectWOrderById(id);
    	Integer orderStatus = selectWOrderById.getOrderStatus();
    	if (orderStatus.intValue() >=3)  return R.error("生产过了");
    	Date getProductStart = wOrderVO.getProductStart();
    	if ( getProductStart== null ) return R.error("没传开始时间");
    	Date endTime = wOrderVO.getProductEnd();
    	if ( endTime == null ) return R.error("没传结束时间");
    	WOrder wOrder = new WOrder();
    	wOrder.setId(id);
    	wOrder.setProductStart(getProductStart);
    	wOrder.setProductEnd(endTime);
    	wOrder.setOrderStatus(3);
    	wOrderMapper.updateWOrder(wOrder );
    	
    	WOrderGood wOrderGood = new WOrderGood();
    	wOrderGood.setOrderId(id);
		List<WOrderGood> selectWOrderGoodList = wOrderGoodMapper.selectWOrderGoodList(wOrderGood );
		for (WOrderGood e : selectWOrderGoodList) {
			WGoodsRecords wGoodsRecords = new WGoodsRecords();
			wGoodsRecords.setOrderId(id);
			wGoodsRecords.setChangeNumber(e.getNumber().intValue());
			wGoodsRecords.setIsIn(1);
			wGoodsRecords.setInType(1);
			wGoodsRecords.setGoodsId(e.getGoodsId());
			wGoodsRecords.setOrderSn(selectWOrderById.getOrderSn());
			iWGoodService.dealWGood(wGoodsRecords );;
		}
    	
    	
    	return R.success();
    }
    @Transactional
    @Override
    public R updateWOrder(WOrderVO wOrderVO) {
    	Long id = wOrderVO.getId();
    	if (id == null ) return R.error("没传id");
    	Long customerId = wOrderVO.getCustomerId();
    	if (customerId == null ) {
    		throw new RuntimeException("没传客户id");
		}
    	SysUser customer = SysUserMapper.selectUserById(customerId);
    	Long deptId = wOrderVO.getDeptId();
    	if (deptId == null ) {
    		throw new RuntimeException("没传工厂id");
		}
    	SysDept dep = sysDeptMapper.selectDeptById(deptId);
    	Long productNumber = wOrderVO.getProductNumber();
    	if (productNumber == null ) {
    		throw new RuntimeException("没传产品数量");
		}
    	
    	WOrder selectWOrderById = wOrderMapper.selectWOrderById(id);
    	Integer orderStatusOld = selectWOrderById.getOrderStatus();
    	if (orderStatusOld >2) {
    		throw new RuntimeException("订单不能修改了");
		}
    	
    	List<WOrderGood> orderGoodList = wOrderVO.getOrderGoodList();
    	if (StringUtils.isEmpty(orderGoodList)) {
			throw new RuntimeException("没传物品");
		}
    	for (WOrderGood wOrderGood : orderGoodList) {
    		String comment = wOrderGood.getComment();
    		if (StringUtils.isEmpty(comment))throw new RuntimeException("没传comment");
    		String pn = wOrderGood.getPn();
    		if (StringUtils.isEmpty(pn))throw new RuntimeException("没传pn");
		}
    	wOrderVO.setCreateTime(DateUtils.getNowDate());
        
    	wOrderGoodMapper.deleteWOrderGoodById(id);
    	
        List<WGood> selectWGoodListByPnList = wGoodMapper.selectWGoodListByPnListNew(orderGoodList, customerId, deptId);
        if (CollectionUtils.isEmpty(selectWGoodListByPnList)) {
        	selectWGoodListByPnList = new ArrayList<>();
		}
        int orderStatus = 1;
        Long canNumber = 0l;
        int i = 0;
        for (WOrderGood e : orderGoodList) {
        	
        	Long number = e.getQuantity()   *  productNumber;
        	e.setNumber(number);
        	Boolean isAdd =true;
        	for (WGood wGood : selectWGoodListByPnList) {
				if (GoodUtil.checkEqu(wGood, e)) {
					e.setGoodsId(wGood.getId());
					isAdd = false;
					if (orderStatus ==  1) {
						Long number2 = wGood.getNumber();
						
						WOrderGood selectWOrderGoodNum = wOrderGoodMapper.selectWOrderGoodNumNotOrderId( wGood.getId(),id);
						Long lockNumber = selectWOrderGoodNum.getNumber();
						if (number2 - lockNumber > 0 ) {
							orderStatus =  2;
						}
					
						long canNumber2 = (number2 - lockNumber )  / e.getQuantity()   > productNumber.longValue() ?   productNumber :
								(number2 - lockNumber )  / e.getQuantity()  ;
						 if (i == 0) {
							 canNumber = canNumber2  ;
						}else{
							if (canNumber2 < canNumber ) {
								canNumber = canNumber2;
							}
						}
						 i++;
					}
				}
			}
        	
        	if (isAdd) {
				WGood wGood = new WGood();
				BeanUtils.copyBeanProp(wGood, e);
				wGood.setNumber(0l);
				wGood.setCustomerId(customerId);
				wGood.setDeptId(deptId);
				wGood.setTotalNumber(0l);
				wGood.setUserNumber(0l);
				wGood.setCreateTime(new Date() );
				wGood.setCustomerName(customer.getUserName());
				wGood.setDeptName(dep.getDeptName());
				wGoodMapper.insertWGood(wGood );
				e.setGoodsId(wGood.getId());
			}
		}
        wOrderVO.setBadNumber(0l);
        wOrderVO.setCanNumber(canNumber);
        wOrderVO.setGoodNumber(0l);
        wOrderVO.setOrderStatus(orderStatus);
        wOrderVO.setCustomerName(customer.getUserName());
        wOrderVO.setDeptName(dep.getDeptName());
        wOrderMapper.updateWOrder(wOrderVO);
        for (WOrderGood e : orderGoodList) {
 			e.setOrderId(wOrderVO.getId());
 			wOrderGoodMapper.insertWOrderGood(e);
 		}
    	return R.success();
    }
    
    /**
     * 新增物料订单
     * 
     * @param wOrder 物料订单
     * @return 结果
     */
    @Transactional
    @Override
    public int insertWOrder(WOrderVO wOrderVO)
    {
    	Long customerId = wOrderVO.getCustomerId();
    	if (customerId == null ) {
    		throw new RuntimeException("没传客户id");
		}
    	SysUser customer = SysUserMapper.selectUserById(customerId);
    	Long deptId = wOrderVO.getDeptId();
    	if (deptId == null ) {
    		throw new RuntimeException("没传工厂id");
		}
    	SysDept dep = sysDeptMapper.selectDeptById(deptId);
    	Long productNumber = wOrderVO.getProductNumber();
    	if (productNumber == null ) {
    		throw new RuntimeException("没传产品数量");
		}
    	
    	List<WOrderGood> orderGoodList = wOrderVO.getOrderGoodList();
    	if (StringUtils.isEmpty(orderGoodList)) {
			throw new RuntimeException("没传物品");
		}
    	for (WOrderGood wOrderGood : orderGoodList) {
    		String comment = wOrderGood.getComment();
    		if (StringUtils.isEmpty(comment))throw new RuntimeException("没传comment");
    		String pn = wOrderGood.getPn();
    		if (StringUtils.isEmpty(pn))throw new RuntimeException("没传pn");
		}
    	wOrderVO.setCreateTime(DateUtils.getNowDate());
        
        
        List<WGood> selectWGoodListByPnList = wGoodMapper.selectWGoodListByPnListNew(orderGoodList, customerId, deptId);
        if (CollectionUtils.isEmpty(selectWGoodListByPnList)) {
        	selectWGoodListByPnList = new ArrayList<>();
		}
        
        int orderStatus = 1;
        Long canNumber = 0l;
        int i = 0;
        for (WOrderGood e : orderGoodList) {
        	
        	Long number = e.getQuantity()   *  productNumber;
        	e.setNumber(number);
        	Boolean isAdd =true;
        	for (WGood wGood : selectWGoodListByPnList) {
				if (GoodUtil.checkEqu(wGood, e) ) {
					e.setGoodsId(wGood.getId());
					isAdd = false;
					if (orderStatus ==  1) {
						Long number2 = wGood.getNumber();
						
						WOrderGood selectWOrderGoodNum = wOrderGoodMapper.selectWOrderGoodNum(wGood.getId());
						Long lockNumber = selectWOrderGoodNum.getNumber();
						if (number2 - lockNumber > 0 ) {
							orderStatus =  2;
						}
					
						long canNumber2 = (number2 - lockNumber )  / e.getQuantity()   > productNumber.longValue() ?   productNumber :
								(number2 - lockNumber )  / e.getQuantity()  ;
						 if (i == 0) {
							 canNumber = canNumber2  ;
						}else{
							if (canNumber2 < canNumber ) {
								canNumber = canNumber2;
							}
						}
						 i++;
					}
				}
			}
        	
        	if (isAdd) {
				WGood wGood = new WGood();
				BeanUtils.copyBeanProp(wGood, e);
				wGood.setNumber(0l);
				wGood.setCustomerId(customerId);
				wGood.setDeptId(deptId);
				wGood.setTotalNumber(0l);
				wGood.setUserNumber(0l);
				wGood.setCreateTime(new Date() );
				wGood.setCustomerName(customer.getUserName());
				wGood.setDeptName(dep.getDeptName());
				wGoodMapper.insertWGood(wGood );
				e.setGoodsId(wGood.getId());
			}
		}
        
        wOrderVO.setOrderSn(DateUtils.dateTimeNow()+RandomStringUtils.randomNumeric(6));
        wOrderVO.setBadNumber(0l);
        wOrderVO.setCanNumber(canNumber);
        wOrderVO.setGoodNumber(0l);
        wOrderVO.setOrderStatus(orderStatus);
        wOrderVO.setCustomerName(customer.getUserName());
        wOrderVO.setDeptName(dep.getDeptName());
        int insertWOrder = wOrderMapper.insertWOrder(wOrderVO);
        for (WOrderGood e : orderGoodList) {
			e.setOrderId(wOrderVO.getId());
			wOrderGoodMapper.insertWOrderGood(e);
		}
        
		return insertWOrder;
    }
    
 

  


    /**
     * 删除物料订单信息
     * 
     * @param id 物料订单主键
     * @return 结果
     */
    @Transactional
    @Override
    public R deleteWOrderById(Long id)
    {
    	WOrder selectWOrderById = wOrderMapper.selectWOrderById(id);
    	Integer orderStatus = selectWOrderById.getOrderStatus();
    	if (orderStatus > 2 ) return R.error("订单不能删除");
    	
    	WOrderOpeara wOrderOpeara =new WOrderOpeara();
    	wOrderOpeara.setType(1);
    	wOrderOpeara.setOrderId(id);
    	List<WOrderOpeara> selectWOrderOpearaList = wOrderOpearaMapper.selectWOrderOpearaList(wOrderOpeara );
    	if (CollectionUtils.isNotEmpty(selectWOrderOpearaList) && selectWOrderOpearaList.size() > 0) {
			return R.error("有发料不能删除");
		}
    	
    	
    	wOrderMapper.deleteWOrderById(id);
    	wOrderGoodMapper.deleteWOrderGoodByOrderId(id);
    	
        return R.success();
    }
    
    @Override
    public R cancelWOrderById(Long id) {
    	WOrder selectWOrderById = wOrderMapper.selectWOrderById(id);
    	Integer orderStatus = selectWOrderById.getOrderStatus();
    	if (orderStatus > 2 ) return R.error("订单不能删除");
    	
    	WOrder order = new WOrder();
    	order.setId(id);
    	order.setOrderStatus(5);
		wOrderMapper.updateWOrder(order );
    	return R.success();
    }
}
